<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="规格名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入规格名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="规格状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择规格状态" clearable>
          <el-option
            v-for="dict in dict.type.sys_normal_disable"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['product:rule:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['product:rule:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['product:rule:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['product:rule:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="ruleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="编号" align="center">
        <template slot-scope="scope">
          {{scope.$index + 1}}
        </template>
      </el-table-column>
      <el-table-column label="名称" align="center" prop="name" />
      <el-table-column label="规格" align="center">
        <template slot-scope="scope">
          <div v-html="scope.row.attr"></div>
        </template>
      </el-table-column>
      <el-table-column label="规格详情" align="center">
        <template slot-scope="scope">
          <div v-html="scope.row.attrValues"></div>
        </template>
      </el-table-column>
      <el-table-column label="规格状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.sys_normal_disable" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center">
        <template slot-scope="scope">
          {{scope.row.params.createByName}}
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['product:rule:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['product:rule:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品规格对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="规格名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入规格名称" />
        </el-form-item>
        <el-form-item label="规格状态">
          <el-radio-group v-model="form.status">
            <el-radio
              v-for="dict in dict.type.sys_normal_disable"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
<!--        TODO 标题-->
        <el-form-item>
          <div v-for="(attr,index) in this.attrValues">
            <el-row>
              <el-col>
                <el-tag
                  :key="attr.key"
                  closable
                  :disable-transitions="false"
                  @close="delAttr(attr.key)">
                  {{attr.key}}
                </el-tag>
              </el-col>
            </el-row>
            <el-row>
              <el-col>
                <el-tag
                  :key="val"
                  v-for="val in attr.values"
                  closable
                  :disable-transitions="false"
                  @close="delValue(attr.key,val)">
                  {{val}}
                </el-tag>
                <el-button v-show="attr.addValButStatus" size="mini" @click="addVal(index)">新增</el-button>
                <el-input v-show="attr.addValInpStatus" v-model="attrValue" placeholder="请输入属性" size="mini" style="width: 150px" @blur="valSumbit(attr.key,index)"></el-input>
              </el-col>
            </el-row>
            <hr>
          </div>
        </el-form-item>
      </el-form>
      <!--   添加规格信息   -->
      <el-button v-show="attrButStatus" @click="showFromAttr">添加规格信息</el-button>

      <!--      添加规格名称 和 规格属性 form表单-->
      <el-form v-show="attrFormStatus" :inline="true" :model="attrForm" class="demo-form-inline">
        <el-form-item label="规格名称">
          <el-input v-model="attrForm.key" placeholder="请输入规格名称"></el-input>
        </el-form-item>
        <el-form-item label="规格属性">
          <el-input v-model="attrForm.vaue" placeholder="请输入规格属性"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="attrSubmit">提交</el-button>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listRule, getRule, delRule, addRule, updateRule } from "@/api/product/rule";

export default {
  name: "Rule",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品规格表格数据
      ruleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        ruleAttr: null,
        status: null,
      },
      // 表单参数
      attrFormStatus : false,
      attrButStatus : true,
      addValButStatus : true,
      addValInpStatus : false,
      attrValue: '',
      attrForm:{
        key:'',
        vaue:''
      },
      attrValues:[],
      form: {

      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "规格名称不能为空", trigger: "blur" }
        ],
        status: [
          { required: true, message: "规格状态不能为空", trigger: "blur" }
        ],
        createBy: [
          { required: true, message: "创建人不能为空", trigger: "blur" }
        ],
        createTime: [
          { required: true, message: "创建时间不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 属性提交 */
    valSumbit(attrKey,attrIndex){
      if (this.attrValue == ''){
        this.$message.warning("属性不可以为空")
        return
      }
      for(var index in this.attrValues){
        if (this.attrValues[index].key == attrKey){
          var values =  this.attrValues[index].values;
          var valIndex= values.indexOf(this.attrValue)
          if (valIndex > -1){
            this.$message.warning("属性已经存在")
            return;
          }
          this.attrValues[index].values.push(this.attrValue)
        }
      }
      this.attrValue='';
      this.attrValues[attrIndex].addValInpStatus = false;
      this.attrValues[attrIndex].addValButStatus = true;
    },
    /** 新增属性 */
    //TODO 问题未解决
    addVal(index){
      //console.log(this.attrValues[index])
      console.log(index)
      //debugger
      this.attrValues[index].addValInpStatus = true;
      this.attrValues[index].addValButStatus = false;
    },
    /** 删除规格名称*/
    delAttr(attrValue){
      var attrIndex = -1;
      for(var index in this.attrValues){
        if (this.attrValues[index].key == attrValue){
            attrIndex = index;
        }
      }
      if (attrIndex !== -1) {
        this.attrValues.splice(attrIndex,1)
      }
    },
    /** 删除规格属性*/
    delValue(attrKey,val){
      var deleteIndex = -1;
      //第一层循环负责找到 规格的对象
      for(var index in this.attrValues){
        if (this.attrValues[index].key == attrKey){
         // attr 就是规格的 对象
         var attr = this.attrValues[index];
         //第二层循环 负责找到 属性所在位置
         for (var valIndex in attr.values){
           if (attr.values[valIndex] == val){
              deleteIndex = valIndex;
           }
         }
         //删除属性
          if (deleteIndex > -1){
            attr.values.splice(deleteIndex,1)
          }
        }
      }
    },
    /** 商品规格详情*/
    attrSubmit(){
      //提交规格信息时 判断 规格名称和规格参数不能为空
      if (this.attrForm.key == '' || this.attrForm.vaue == ''){
        this.$message.warning("规格信息不可以为空")
        return
      }
      // 判断是否有重复的规格 如果有重复的规格进行追加
      for(var index in this.attrValues){
        if (this.attrValues[index].key == this.attrForm.key){
          if(this.attrValues[index].values.indexOf(this.attrForm.vaue)> -1){
            this.$message.warning("["+this.attrForm.key+"]规格属性已经含有["+this.attrForm.vaue+"]")
            return;
          }
          this.attrValues[index].values.push(this.attrForm.vaue)
          this.attrValues[index].addValButStatus = true;
          this.attrForm = {
            key:'',
            vaue:''
          };
          this.showAddAttr()
          return;
        }
      }
      //如果没有重复的，那么就创建一个新的 规格 对象
      var attr = {
        key: this.attrForm.key,
        values:[this.attrForm.vaue],
        addValButStatus : true
      }
      this.attrValues.push(attr)
      this.attrForm = {
        key:'',
        vaue:''
      };
      this.showAddAttr()
    },
    //添加规格信息按钮
    showFromAttr(){
      this.attrFormStatus = true;
      this.attrButStatus = false;
    },
    showAddAttr(){
      this.attrFormStatus = false;
      this.attrButStatus = true;
    },
    /** 查询商品规格列表 */
    getList() {
      this.loading = true;
      listRule(this.queryParams).then(response => {
        var rows = response.rows;
        rows.forEach(row =>{
          console.log(row.ruleAttr)
          var ruleAttr = JSON.parse(row.ruleAttr)
          var attrHtml = "";
          var attrValuesHtml = "";
          //进行循环 ruleAttr
          ruleAttr.forEach(attr =>{
            attrHtml +="<p>"+attr.key+"</p>";
            var values = attr.values;
            //attrValuesHtml += "<p>"+attr.values+"</p>"
            attrValuesHtml += "<p>";
            values.forEach((value,status = false) =>{
              if (status){ attrValuesHtml+= "," }else { status = true }
              attrValuesHtml+= value;
            })
            attrValuesHtml += "</p>";
          })
          row.attr = attrHtml;
          row.attrValues = attrValuesHtml;
        })
        this.ruleList = rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        name: null,
        ruleAttr: null,
        status: "0",
        revision: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null
      };
      this.attrValues = [];
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加商品规格";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRule(id).then(response => {
        this.form = response.data;
        //JSON
        this.attrValues = JSON.parse(this.form.ruleAttr);
        this.open = true;
        this.title = "修改商品规格";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            //转JSON  JSON.stringify(this.attrValues);
            this.form.ruleAttr = JSON.stringify(this.attrValues);
            updateRule(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.ruleAttr = JSON.stringify(this.attrValues);
            addRule(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.attrValues = [];
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品规格编号为"' + ids + '"的数据项？').then(function() {
        return delRule(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('product/rule/export', {
        ...this.queryParams
      }, `rule_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
<style>
.el-tag + .el-tag {
  margin-left: 10px;
}
.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
</style>
